package edu.ptu.shortlink.project.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import edu.ptu.shortlink.project.dao.entity.LinkNetworkStatsDO;
import edu.ptu.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO;
import edu.ptu.shortlink.project.dto.req.ShortLinkStatsReqDTO;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.project.dao.mapper
 * @Author: HYJ
 * @CreateTime: 2025-05-07  16:26
 * @Description: 短链接访问网络统计持久层接口
 * @Version: 1.0
 */
public interface LinkNetworkStatsMapper extends BaseMapper<LinkNetworkStatsDO> {

    @Insert("INSERT INTO t_link_network_stats ( full_short_url, gid, date, cnt, network, create_time, update_time, del_flag ) "
            + "VALUES (#{linkNetworkStats.fullShortUrl},#{linkNetworkStats.gid},#{linkNetworkStats.date}, #{linkNetworkStats.cnt}, #{linkNetworkStats.network}, NOW(), NOW(), 0 ) "
            + "ON DUPLICATE KEY UPDATE cnt = cnt + #{linkNetworkStats.cnt};")
    void shortLinkNetworkStatsInc(@Param("linkNetworkStats") LinkNetworkStatsDO linkNetworkStats);

    /**
     * 根据短链接获取指定日期内访问网络统计数据
     */
    @Select("SELECT " +
            "    tlns.network, " +
            "    SUM(tlns.cnt) AS cnt " +
            "FROM " +
            "    t_link tl INNER JOIN " +
            "    t_link_network_stats tlns ON tl.full_short_url = tlns.full_short_url " +
            "WHERE " +
            "    tlns.full_short_url = #{param.fullShortUrl} " +
            "    AND tl.gid = #{param.gid} " +
            "    AND tl.del_flag = '0' " +
            "    AND tl.enable_status = #{param.enableStatus} " +
            "    AND tlns.date BETWEEN #{param.startDate} and #{param.endDate} " +
            "GROUP BY " +
            "    tlns.full_short_url, tl.gid, tlns.network;")
    List<LinkNetworkStatsDO> listNetworkStatsByShortLink(@Param("param") ShortLinkStatsReqDTO requestParam);

    /**
     * 根据分组获取指定日期内访问网络统计数据
     */
    @Select("SELECT " +
            "    tlns.network, " +
            "    SUM(tlns.cnt) AS cnt " +
            "FROM " +
            "    t_link tl INNER JOIN " +
            "    t_link_network_stats tlns ON tl.full_short_url = tlns.full_short_url " +
            "WHERE " +
            "    tlns.gid = #{params.gid} " +
            "    AND tlns.date BETWEEN #{params.startDate} and #{params.endDate} " +
            "    AND tl.del_flag = '0' " +
            "    AND tl.enable_status = '0' " +
            "GROUP BY " +
            "    tlns.gid, tlns.network;")
    List<LinkNetworkStatsDO> listNetworkStatsByGroup(@Param("params") ShortLinkGroupStatsReqDTO requestParam);
}
